package com.happe.foodeasy.client.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.happe.foodeasy.client.ImgClient;
import com.happe.foodeasy.dto.PositionImageDTO;
import com.happe.foodeasy.util.ManageSystemInfoContainer;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component("imgClient")
public class ImgClientImpl implements ImgClient {
    @Override
    public List<PositionImageDTO> selectTargetPositionImgInfo(Integer positionId) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(ManageSystemInfoContainer.retrieveUrl() + "positionImage/retrievePositionImageInfo.do");
        List<NameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("positionId", positionId + ""));

        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String jsonResult = EntityUtils.toString(entity, "UTF-8");
                    return JSON.parseObject(jsonResult, new TypeReference<List<PositionImageDTO>>() {
                    });
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public InputStream selectTargetPositionImg(Integer imageId) {
        CloseableHttpClient httpclient = HttpClients.custom().setKeepAliveStrategy(keepAliveStrategy()).build();
        HttpPost httppost = new HttpPost(ManageSystemInfoContainer.retrieveUrl() + "positionImage/retrieveTargetPositionImage.do");
        List<NameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("imageId", imageId + ""));
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            InputStream result = null;
            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = entity.getContent();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    IOUtils.copy(result, out);
                    result = new ByteArrayInputStream(out.toByteArray());
                }
            }
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private ConnectionKeepAliveStrategy keepAliveStrategy() {
        return new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
// Honor 'keep-alive' header
                HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (NumberFormatException ignore) {
                        }
                    }
                }
                return 20 * 1000;
            }
        };
    }
}
